<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ShortcutWord extends Base
{
    protected $table = 'shortcut_word';

    //快捷语缓存
    protected $shortcutWordAllKey = 'SHORTCUTWORD:ALL';//string SHORTCUTWORD:ALL => {string}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //添加快捷语
    public function createShortcutWord($data)
    {
        $id = DB::table($this->table)->insertGetId($data);

        $cacheKey = $this->shortcutWordAllKey;
        Redis::del($cacheKey);

        return $id;
    }

    //编辑快捷语
    public function updateShortcutWord($id, $params)
    {
        $upData = [];
        if(!empty($params['content'])) {
            $upData['content'] = $params['content'];
        }
        if(!empty($params['data_type'])) {
            $upData['data_type'] = $params['data_type'];
        }
        if(isset($params['sort'])) {
            $upData['sort'] = $params['sort'];
        }
        if(!empty($params['is_delete'])) {
            $upData['is_delete'] = $params['is_delete'];
        }
        if(!empty($params['admin_id'])) {
            $upData['admin_id'] = $params['admin_id'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->table)->where('id', $id)->update($upData);

        $cacheKey = $this->shortcutWordAllKey;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取所有快捷语
     */
    public function shortcutWordAll(){
        $cacheKey = $this->shortcutWordAllKey;
        $list = Redis::get($cacheKey);
        if(empty($list)){
            $listEx = ['user'=>[], 'anchor'=>[]];
            $data = DB::table($this->table)->where('is_delete', 0)->select(['id','content','data_type','sort'])->orderBy('sort', 'asc')->get()->toArray();
            $data = self::objToArray($data);
            if(!empty($data)) {
                foreach($data as $val) {
                    //用户
                    if($val['data_type'] == 1) {
                        $listEx['user'][] = $val;
                    }
                    //主播
                    if($val['data_type'] == 2) {
                        $listEx['anchor'][] = $val;
                    }
                }
                Redis::setex($cacheKey, 86400, json_encode($listEx));
            }
            $list = $listEx;
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

}
